﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace CRMLayer
{
    public class CapsuleCRM
    {

        public static string QueryPartyIDByEmail(string Email)
        {
            string crmToken = ConfigurationManager.AppSettings["CapsuleCRMToken"];
            string uri = string.Format("https://ua.capsulecrm.com/api/party?email={0}", Email);

            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential(crmToken, "x");
            HttpClient client = new HttpClient(handler);
            client.BaseAddress = new Uri(uri);

            // Add an Accept header for XML format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            // List data response.
            HttpResponseMessage response = client.GetAsync("").Result;  // Blocking call!
            string dataObjects;
            if (response.IsSuccessStatusCode)
                // Parse the response body. Blocking!
                dataObjects = response.Content.ReadAsStringAsync().Result;
            else
                throw new Exception(string.Format("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase));

            XDocument doc = XDocument.Parse(dataObjects);

            string partyID = (from node in doc.Descendants("parties")
                              from node2 in node.Descendants("person")
                              select node2.Element("id").Value).FirstOrDefault();
            if (string.IsNullOrEmpty(partyID))
                partyID = (from node in doc.Descendants("parties")
                           from node2 in node.Descendants("organisation")
                           select node2.Element("id").Value).FirstOrDefault();

            return partyID;
        }

        public static void AddNewCase(string Email, string BookingID, string FlightID, string ClientNameOnInvoice, string ClientDocumentID, string InvoiceID, string InvoiceLink)
        {
            string crmToken = ConfigurationManager.AppSettings["CapsuleCRMToken"];
            string partyID = QueryPartyIDByEmail(Email);
            string uri = string.Format("https://ua.capsulecrm.com/api/party/{0}/kase", partyID);

            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential(crmToken, "x");
            HttpClient client = new HttpClient(handler);

            string kase = string.Format("<kase><status>OPEN</status><name>New Flight Reservation</name><description>Booking : {0} - Flight : {1} - Client Name On Invoice : {2} - Client Document ID : {3} - InvoiceID : {4} - InvoiceLink : {5}</description></kase>", BookingID, FlightID, ClientNameOnInvoice, ClientDocumentID, InvoiceID, InvoiceLink);
            var data = new StringContent(kase, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync(uri, data).Result;

            response.EnsureSuccessStatusCode();
        }

        public static void AddOwnOpportunity(string Email, string BookingID, string FlightID, string ClientNameOnInvoice, string ClientDocumentID, string InvoiceID, double Value)
        {
            string crmToken = ConfigurationManager.AppSettings["CapsuleCRMToken"];
            string partyID = QueryPartyIDByEmail(Email);
            string uri = string.Format("https://ua.capsulecrm.com/api/party/{0}/opportunity", partyID);

            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential(crmToken, "x");
            HttpClient client = new HttpClient(handler);

            string opportunity = string.Format(@"<opportunity>
  <name>Flight Reservation</name>
  <description>Booking: {0} | Flight: {1} | Client Name: {2} | Client Document: {3} | Invoice: {4}</description>
  <currency>EUR</currency>
  <value>{5}</value>
  <durationBasis>DAY</durationBasis>
  <duration>1</duration>
  <expectedCloseDate>{6}</expectedCloseDate>
  <milestone>Won</milestone>
  <probability>100</probability>
  </opportunity>", BookingID, FlightID, ClientNameOnInvoice, ClientDocumentID, InvoiceID, Value, DateTime.Now.ToString());

            var data = new StringContent(opportunity, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync(uri, data).Result;

            response.EnsureSuccessStatusCode();
        }

        public static void AddCompany(string CompanyName, string Email)
        {
            string crmToken = ConfigurationManager.AppSettings["CapsuleCRMToken"];
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential(crmToken, "x");

            HttpClient client = new HttpClient(handler);

             string person = string.Format(@"<person>
  <contacts>
    <email>
      <type>Home</type>
      <emailAddress>{0}</emailAddress>
    </email>
  </contacts>
  <title>Mr</title>
  <firstName>{1}</firstName>
  <lastName>.</lastName>
  <about>Adicionado via AAMS API</about>
</person>", Email, CompanyName);
            var data = new StringContent(person, Encoding.UTF8, "text/xml");

            // Add an Accept header for xml format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            HttpResponseMessage response = client.PostAsync("https://ua.capsulecrm.com/api/person", data).Result;

            string dataObjects = response.Content.ReadAsStringAsync().Result;
        }
    }
}
